package com.zq.sdklib.transform.cost.asm

import org.objectweb.asm.AnnotationVisitor
import org.objectweb.asm.ClassVisitor
import org.objectweb.asm.MethodVisitor
import org.objectweb.asm.Opcodes

class AsmMethodCostClassVisitor(api: Int, classVisitor: ClassVisitor?) : ClassVisitor(api, classVisitor) {

    var owner = ""
    // 是否抽象方法或者接口
    private var isABSClass = false

    override fun visit(
        version: Int,
        access: Int,
        name: String?,
        signature: String?,
        superName: String?,
        interfaces: Array<out String>?
    ) {
        super.visit(version, access, name, signature, superName, interfaces)
        owner = name?:""
        isABSClass = access and Opcodes.ACC_ABSTRACT > 0 || access and Opcodes.ACC_INTERFACE > 0
        println("visit: version:$version access:$access name:$name signature:$signature superName:$superName interfaces:$interfaces")
    }

    override fun visitMethod(
        access: Int,
        name: String?,
        descriptor: String?,
        signature: String?,
        exceptions: Array<out String>?
    ): MethodVisitor {
        println("visitMethod: access:$access name:$name descriptor:$descriptor signature:$signature exceptions:$exceptions")
        if (!isABSClass) {
            cv?.let {
                val methodVisitor = it.visitMethod(access, name, descriptor, signature, exceptions)
                println("方法处理 $owner -> $name")
                return AsmMethodCostMethodVisitor(api, methodVisitor, access, name, descriptor)
            }
        }
        return super.visitMethod(access, name, descriptor, signature, exceptions)
    }

    override fun visitAnnotation(descriptor: String?, visible: Boolean): AnnotationVisitor {
        println("visitAnnotation: descriptor:$descriptor visible:$visible")
        return super.visitAnnotation(descriptor, visible)
    }

    override fun visitEnd() {
        super.visitEnd()
        println("visitEnd: $owner")

    }
}